
<!--登录 退出组件-->
<script setup>
import {doGet, doPost, doPut} from "../util/request.js";
  import {TOKEN_NAME} from "../util/constant.js";
import {ArrowDown, User} from "@element-plus/icons-vue";
import {computed, onMounted, ref} from "vue";
import {confirmMessage, showMessage} from "../util/message.js";
import {useStore} from "vuex";
// 获取用户信息 vuex 获取用户
const store = useStore();
const loginUser = computed(() => store.state.loginUser);
onMounted(() => {
  store.dispatch('fetchUserInfo');
});
//创建用户对象



/*onMounted(()=>{
  //加载用户信息
  doGet("/api/user/info",{}).then((resp)=>{
    if (resp.data.code === 200){
      //获取用户信息
      loginUser.value = resp.data.data;

    }else {
      showMessage("查询失败"+resp.data.msg,"error")
    }
  })
})*/




/* --------------------退出------------------*/
  const logOut = () =>{
    confirmMessage("确定退出").then(()=>{
      doPost("/api/logout",{}).then((resp)=>{
        if (resp.data.code === 200){
          showMessage("退出成功",'success')
          //清除本地存储Token
          localStorage.removeItem(TOKEN_NAME)
          sessionStorage.removeItem(TOKEN_NAME)
          //跳转到登录页面
          window.location.href = "/";
        }
      })
    })

  }
/* --------------------查询登录人信息------------------*/
// 我的资料窗口显示状态
const myProfileDialogVisible = ref(false)
// 我的资料信息对象
let myProfileInfo = ref({})
// 显示我的资料弹出窗口
const showMyProfile = ()=>{
  // 显示我的资料弹出窗口
  myProfileDialogVisible.value = true
  // 查询登录用户信息
  doGet('/api/user/infoUser',{}).then(resp => {
    console.log(resp)
    if (resp.data.code === 200) {
      console.log(resp.data.data)
      myProfileInfo.value = resp.data.data;

    } else {
      showMessage('数据加载失败，请稍后重试.','error')
    }
  })
}
/* --------------------修改密码------------------*/
// 修改密码窗口显示状态
const updataPassword = ref(false)
//修改密码表单对象
const rulePassword = ref({})
//比较新密码俩次一样
const comparePwd=(rule,value,callback)=>{
  if (value !== rulePassword.value.newPwd){
    callback(new Error('两次密码不一致'))
  }else {
    callback()
  }
}
//验证旧密码
const compareBackstagePwd=(rule,value,callback)=>{
    doGet('/api/user/backstagePwd',{
      oldPwd:value
    }).then(resp => {
      if (resp.data.code === 200) {
        //获取比较结果
        if (!resp.data.data ){
          callback(new Error('旧密码不正确'))
        }else {
          callback()
        }
      }
      else {
        callback()
      }
    })
}

//表单验证规则
const rulesFrom={
  oldPwd: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' },
      { validator : compareBackstagePwd ,trigger:'blur'},
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'}

  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'}

  ],

  Pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'},
    { validator : comparePwd ,trigger:'blur'}
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  accountNoExpired: [
    {required: true, message: '请选择', trigger: 'change'},
  ],
  credentialsNoExpired: [
    {required: true, message: '请选择', trigger: 'change'},
  ],
  accountNoLocked: [
    {required: true, message: '请选择', trigger: 'change'},
  ],
  accountEnabled: [
    {required: true, message: '请选择', trigger: 'change'},
  ]
}
// 表单提交对象
const modifyRuleFormRef = ref({})

//提交修改密码
const ofPassword = (formEL) =>{
  if(!formEL)  return

    formEL.validate(valid => {
        doPut("/api/user/updataPwd", {
          loginPwd:  rulePassword.value.newPwd
          }).then((resp) => {
            if (resp.data.code === 200) {
              showMessage('修改成功','success')
              //清空Token
              localStorage.removeItem(TOKEN_NAME)
              sessionStorage.removeItem(TOKEN_NAME)
              window.location.href = "/";
            }else {
              showMessage("修改失败"+resp.data.msg,'error')
            }
          })
    })
}






</script>

<template>
  <el-dropdown>

          <span class="el-dropdown-link" style="font-size: 20px">
            <el-icon><User /></el-icon>
          {{ loginUser.name }}
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="showMyProfile">我的资料</el-dropdown-item>
        <el-dropdown-item @click="updataPassword = true">修改密码</el-dropdown-item>
        <el-dropdown-item @click="logOut">退出</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>

      <!--我的资料弹出窗口-->
      <el-dialog
          v-model="myProfileDialogVisible"
          title="我的资料"
          width="500"
          :close-on-click-modal=false
          >

        <el-form label-width="auto" style="max-width: 600px;text-align: left">
          <el-form-item label="用户标识">：
            {{ myProfileInfo.id }}
          </el-form-item>
          <el-form-item label="帐号">：
            {{ myProfileInfo.loginAct }}
          </el-form-item>
          <el-form-item label="姓名">：
            {{ myProfileInfo.name }}
          </el-form-item>
          <el-form-item label="手机号码">：
            {{ myProfileInfo.phone }}
          </el-form-item>
          <el-form-item label="邮箱">：
            {{myProfileInfo.email}}
          </el-form-item>
          <el-form-item label="最近登录时间">：
            {{ myProfileInfo.lastLoginTime }}
          </el-form-item>
          <el-form-item label="编辑者">：
            {{ myProfileInfo.editByName }}
          </el-form-item>
          <el-form-item label="创建者">：
            {{ myProfileInfo.createByName }}
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="myProfileDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
  <!--修改密码-->
  <el-dialog
      v-model="updataPassword"
      title="修改密码"
      width="500"
      :close-on-click-modal=false
      :show-close=false
      align-center
  >
    <el-form
        ref="modifyRuleFormRef"
        style="max-width: 600px"
        :model="rulePassword"
        status-icon
        :rules="rulesFrom"
        label-width="auto"
    >
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input v-model="rulePassword.oldPwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="rulePassword.newPwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确定密码" prop="Pwd">
        <el-input v-model="rulePassword.Pwd" type="password" autocomplete="off" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updataPassword = false">取消</el-button>
        <el-button type="primary" @click="ofPassword(modifyRuleFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>



</template>

<style scoped>

</style>
